﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;

namespace LIMS.Common
{
    /// <summary>
    /// 全文检索：公共转换类
    /// </summary>
    public static class ConventerCommon
    {
        /// <summary>
        /// 将IEnumerable类型转换为DataTable类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="varList"></param>
        /// <returns></returns>
        public static System.Data.DataTable LinqToDataTable<T>(IEnumerable<T> varList)
        {
            var dt = new System.Data.DataTable();
            var ps = typeof(T).GetProperties().ToList();
            ps.ForEach(p => { dt.Columns.Add(p.Name, p.PropertyType); });
            foreach (T item in varList)
            {
                var dr = dt.NewRow();
                var vs = ps.Select(p => p.GetValue(item, null));
                var ls = vs.ToList();
                int i = 0;
                ls.ForEach(c => dr[i++] = c);
                dt.Rows.Add(dr);
            }
            return dt;
        }

        /// <summary>
        ///  将IEnumerable类型转换为DataTable类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="varList"></param>
        /// <returns></returns>
        public static System.Data.DataTable ToDataTable<T>(IEnumerable<T> varList)
        {
            var dt = new System.Data.DataTable();
            var ps = System.ComponentModel.TypeDescriptor.GetProperties(typeof(T));
            foreach (System.ComponentModel.PropertyDescriptor dp in ps)
            {
                dt.Columns.Add(dp.Name, dp.PropertyType);
            }
            foreach (T item in varList)
            {
                var dr = dt.NewRow();
                foreach (System.ComponentModel.PropertyDescriptor dp in ps)
                {
                    dr[dp.Name] = dp.GetValue(item);
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

        public static System.Data.DataView FullTextSearch(this System.Data.DataTable dataTable, String[] keyWords)
        {
            var query = dataTable.AsEnumerable().
                    Where<System.Data.DataRow>(row =>
                        keyWords.All(keyword =>
                            row.ItemArray.Select(
                                p => p.ToString()
                            ).
                            Any<String>(
                                s => s.Contains(keyword)
                            )
                        )
                    );
            return query.AsDataView();
        }

    }
}
